<template>
  <div align="center">

  </div>
</template>

<script>

export default {
  data () {
    return {
      // url: "ws://47.107.99.99:8080/websocket/" + this.$store.getters.userInfo.userName,
      url: 'ws://127.0.0.1:8080/websocket/' + this.$store.getters.userInfo.userName,
      message: 'HELLO',
      text_content: '',
      ws: null,
      progressNum: 0
    }
  },
  beforeDestroy () {
    clearInterval(this.time)
    this.ws.close()
  },
  methods: {
    join () {
      const wsuri = this.url
      console.log(this.$store.getters.userInfo.userName, '开始建立链接：' + wsuri)
      this.ws = new WebSocket(wsuri)
      const self = this
      this.ws.onopen = function (event) {
        console.log(event)
        // 当WebSocket创建成功时，触发onopen事件
        // this.ws.send('hello') // 将消息发送到服务端
        self.text_content = self.text_content + '已经打开连接!' + '\n'
      }
      this.ws.onmessage = function (event) {
        try {
          const res = JSON.parse(event.data)
          // 当客户端收到服务端发来的消息时，触发onmessage事件，参数e.data包含server传递过来的数据
          if (res.code === 1) {
            self.$emit('success')
          }
          if (res.code === 2) {
            self.$emit('message', res)
          }
          if (res.code === 3) {
            self.ws.close()
            self.$emit('close', res)
          }
          if (res.code === 4) {
            self.ws.close()
            self.$emit('error', res)
          }
        } catch (err) {
          console.log(err)
          self.ws.close()
          self.$emit('error')
        }
      }
      this.ws.onclose = function (event) {
        // 当客户端收到服务端发送的关闭连接请求时，触发onclose事件
        self.text_content = self.text_content + '已经关闭连接!' + '\n'
      }
      this.ws.onerror = e => {
        // 如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
        this.ws.close()
        this.$emit('error')
        this.$message.error('连接异常')
      }
    },
    exit () {
      if (this.ws) {
        this.ws.close()
        this.ws = null
      }
    },
    send () {
      if (this.ws) {
        this.ws.send(this.message)
      } else {
        alert('未连接到服务器')
      }
    }
  }
}
</script>
